package com.xtecher.app.column.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xtecher.app.MainActivity;
import com.xtecher.app.R;
import com.xtecher.app.base.BaseActivity;
import com.xtecher.app.utils.SplashUtils;

public class SplashActivity extends BaseActivity {
    private RelativeLayout activitySplash;
    private ImageView imgSplash;
    private LinearLayout linStep;
    private TextView tvDuration;

    Handler handler = new Handler();
    private int duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        initView();
        if (SplashUtils.isBefore(this, System.currentTimeMillis())) {
            String image = SplashUtils.getImage(this);
            duration = SplashUtils.getDuration(this);
            linStep.setVisibility(SplashUtils.isGuo(this) ? View.VISIBLE : View.GONE);
            Glide.with(this)
                    .load(image)
                    .centerCrop()
                    .into(imgSplash);
            handler.postDelayed(runnable, 1000);
        } else {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (duration == 0) {
                handler.removeCallbacks(runnable);
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish();
                return;
            }
            duration--;
            tvDuration.setText("" + duration);
            handler.postDelayed(this, 1000);
        }
    };

    private void initView() {
        activitySplash = (RelativeLayout) findViewById(R.id.activity_splash);
        imgSplash = (ImageView) findViewById(R.id.img_splash);
        linStep = (LinearLayout) findViewById(R.id.lin_step);
        tvDuration = (TextView) findViewById(R.id.tv_duration);

        linStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(runnable);
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        handler.removeCallbacks(runnable);
        finish();
    }
}
